package com.suxii.handler;

import com.suxii.pojo.ChatMsg;
import com.suxii.pojo.LoginMsg;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


@Slf4j
@ChannelHandler.Sharable
@Component("LOGIN_HANDLER")
public class LoginHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        LoginMsg loginMsg = (LoginMsg) msg;
        int uid = loginMsg.getUid();
        String password = loginMsg.getPassword();
        // 判断当前channel是否登录
        if (LoginMsg.users.get(ChannelsHandler.uidlMap.get(ctx.channel())) != null) {
            log.info("已经登录");
            // 临时将uid改为发送人，password改为内容
            super.channelRead(ctx,new ChatMsg(String.valueOf(uid), uid, password));
        } else {
            if (loginMsg.isUser(uid, password)) {
                log.info("登录成功");
                ChannelsHandler.bindChannel(uid, ctx.channel());
                //super.channelRead(ctx, new ChatMsg(String.valueOf(uid), uid, "登录成功"));

                // 以自己的uid作为key，hset 目标uid，消息内容
                HashOperations msgRedis = redisTemplate.opsForHash();
                msgRedis.keys(String.valueOf(uid)).forEach(aimUid -> {
                    String context = (String)msgRedis.get(String.valueOf(uid), aimUid);
                    ctx.channel().writeAndFlush(new ChatMsg(String.valueOf(aimUid),Integer.parseInt((String) aimUid),context));
                    log.info("{} 发消息:{}",aimUid,context);
                    //删除缓存
                    msgRedis.delete(String.valueOf(uid),aimUid);
                });
                //log.info("{}",redisTemplate.opsForHash().get("123","222"));

            } else {
                log.info("验证失败");
                ctx.channel().writeAndFlush(new ChatMsg("0", 0, "登录失败"));
            }
        }
    }
}
